/*
* $Id: TableHeader.cpp 8 2010-01-06 17:25:39Z volok-aleksej@yandex.ru $
*
* Copyright 2009 by Volokitin Alexey
* All rights reserved
*
*/
#include "Common/include.h"
#include <tinyxml.h>
#include "TableHeader.h"

CTableHeader::CTableHeader(const std::tstring& strName, int nId)
: tableHeader(strName, nId), CItemTable(CCommonFunction::GetBeeColor()){
	int cx = GetXmlCx();
	m_size = GetDefaultSize(cx);
}
CTableHeader::~CTableHeader(){
	SetXmlCx();
}

void CTableHeader::SetPos(CPoint pos, bool bNextParent){
	CSize diffSize = m_pos - pos;
	m_pos = pos;
	if(m_pNext){
		CPoint posNext = ((CTableHeader*)m_pNext)->GetPos();
		((CTableHeader*)m_pNext)->SetPos(CPoint(m_pos.x + m_size.cx, posNext.y), bNextParent);
	}
}

void CTableHeader::SetSize(CSize size){
	m_size = size;
}

bool CTableHeader::IsInRect(CPoint pos){
	return pos.x > m_pos.x && pos.y > m_pos.y &&
		pos.x < m_pos.x + m_size.cx - 2 && pos.y < pos.y + m_size.cy;
}

bool CTableHeader::IsAtBorder(CPoint pos){
	return pos.x > m_pos.x + m_size.cx - 2 && pos.y > m_pos.y &&
		pos.x < m_pos.x + m_size.cx + 2 && pos.y < m_pos.y + m_size.cy;
}

int CTableHeader::GetXmlCx(){
	int cx = 0;
	TiXmlDocument xml("table.xml");
	if(xml.LoadFile(TIXML_ENCODING_UTF8)){
		TiXmlElement* root = xml.RootElement();
		if(!root)
			return cx;
		for(TiXmlElement* element = root->FirstChildElement("header"); element; element = element->NextSiblingElement("header")){
			int id = 0, type = 0;
			element->Attribute("id", &id);
			if(id == m_nId){
				element->Attribute("size", &cx);
				break;
			}
		}
	}
	return cx;
}

void CTableHeader::SetXmlCx(){
	TiXmlDocument xml("table.xml");
	if(!xml.LoadFile(TIXML_ENCODING_UTF8)){
		TiXmlDeclaration decl("1.0", "UTF-8", ""); 
		xml.InsertEndChild(decl);
		TiXmlElement root("table");
		xml.InsertEndChild(root);
	}
	TiXmlElement* root = xml.RootElement();
	TiXmlElement* element;
	for(element = root->FirstChildElement("header"); element; element = element->NextSiblingElement("header")){
		int id = 0, type = 0;
		element->Attribute("id", &id);
		if(id == m_nId){
			break;
		}
	}
	if(!element){
		TiXmlElement elem("header");
		elem.SetAttribute("id", m_nId);
		element = root->InsertEndChild(elem)->ToElement();
	}
	element->SetAttribute("size", m_size.cx);
	xml.SaveFile();
}